from flask import Blueprint,request,jsonify,make_response
from  flask import  current_app as app
import json
import os
import uuid
from utils.mylist import myfile
from utils.db import  db
from utils.comm import xtree
from utils.myes import Es
from utils.comm import  get_data
from utils.jwts import myjwt
from utils.myacl import acl
from utils.redisconn import  r

bp_user = Blueprint('users',__name__)


#用户登录
@bp_user.route('/login/',methods=['POST'])
def login():
    data = get_data()
    sql = "select * from users where mobile='%s'"%(data['mobile'])
    res = db.find_one(sql)
    #判断用户是否存在
    if res:
        if res['password'] == data['password']:
            #生成token
            data = {'data':{'mobile':res['mobile'],'userid':res['id'],'name':res['name']}}
            token = myjwt.jwt_encode(data)
            #用户权限 该用户权限集 这边只获取前端权限
            resall = acl.get_page_resource(res['id'])
            #把前端所有权限存入redis
            key = 'interface'+str(res['id'])
            r.set_add(key,resall)
            return jsonify({"code":200,'mes':'登录成功','userid':res['id'],'name':res['name'],'mobile':res['mobile'],'token':token,'pagelist':resall})
        else:
            return jsonify({"code":20030,'mes':'用户名或密码有误'})
    else:
        return jsonify({"code":20020,'mes':'该用户不从在'})


#构建简单的2层分类
def gettwocate(data):
    lst = []
    idlist = []
    #把顶级id方在lst里
    for i in data:
        id = i['pid']
        #去掉重复的父id  列入 有4个 5 5 9 15  只剩下5 9 15 就是顶级父类
        if id not in idlist:
            lst.append({'id':id,'name':i['pname'],'son':[]})
            idlist.append(id)
    #循环添加数据的列表 需要下表
    for i,value in enumerate(lst):
        for j in data:
            # print(j)
            if value['id'] == j['pid']:
                lst[i]['son'].append({'id':j['id'],'name':j['name'],'url':j['url']})

    return  lst




#用户资源
@bp_user.route('/usermanage/')
async def usermanage():
    uid  = 1
    #根据用户id查看用户有哪些权限
    # sql = "select r.id,r.name,re.name as pname,re.id as pid,r.url from resource as r left join user_resource as ur on r.id=ur.resourceid left join resource as re on  r.pid=re.id   where r.type=1 and ur.userid=%d"%(int(uid))
    sql = "select r.id,r.name,re.name as pname,re.id as pid,r.url from resource as r left join user_resource as ur on r.id=ur.resourceid left join resource as re on  r.pid=re.id    where r.type=1 and ur.userid=%d"%(int(uid))
    res = db.find_all(sql)
    lst = gettwocate(res)
    return jsonify({'code':200,'list':lst})


#穿梭表  获取管理员权限
@bp_user.route('/getadmin/')
async def getadmin():
    uid = 4
    #先查看管理员对用那个角色  角色对应那些资源 r.id,
    sql = "select r.name as rname from users as u left join user_jue as uj on u.id=uj.userid left join jue_resource as jr on uj.jueid=jr.jueid left join resource as r on jr.resourceid = r.id where u.id=%d"%(int(uid))

    res = db.find_all(sql)
    return jsonify({'code':200,'list':res})